//app.js
import config from "./config.js";
const base = config;
//消息队列
let socketMsgQueue = []

App({
  onLaunch: function() {
    var that = this;
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    // 获取openID
    /**wx.login({
      success: function(res) {
        wx.request({
          url: base.CheckOpenId,
          data: {
            code: res.code
          },
          success: function(res) {
            console.log("openId" + res.data.data.openid);
            wx.setStorageSync('openID', res.data.data.openid);
            // if (wx.getStorageSync("session") == null) {
            //   wx.setStorageSync("session", res.data.session);
            //   console.log("session:" + res.data.session);
            // }

          }
        })
      }
    })
    //自动登录
    //判断是否登录
    var openID = wx.getStorageSync('openID'),
      session = wx.getStorageSync('session');
    console.log("session" + session);
    if (openID != null && session != null) {
      wx.request({
        url: base.isLogin,
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Cookie': session
        },
        success: function(res) {
          console.log(res);
          //已登录
          if (res.data.status == 200) {
            wx.showToast({
              title: '登陆成功',
              icon: 'none',
              mask: true,
              duration: 1000
            })
            that.globalData.getUserInfo();
          } else {
            //未登录
            wx.showToast({
              title: '初始化...',
              icon: "loading",
              mask: true
            })
            // wx.setStorageSync("session", res.data.session);
            // console.log("session:" + res.data.session);
            // session = res.data.session;
            wx.request({
              url: base.autoLogin,
              header: {
                'content-type': 'application/x-www-form-urlencoded',
                'Cookie': session
              },
              data: {
                openId: openID
              },
              success: function(res) {
                console.log(res);
                wx.hideLoading();

                if (res.data.status == 200) {
                  wx.showToast({
                    title: "初始化...",
                    icon: "loading",
                    mask: true,
                    duration: 1000
                  })
                  setTimeout(function() {
                    that.globalData.getUserInfo();
                  }, 1000);
                } else {
                  wx.showToast({
                    title: "登录失效",
                    icon: "none",
                    mask: true,
                    duration: 1000
                  })

                }
              }
            })

          }
        }
      })
    } **/

    //判断机型
    var model, reg = /iphone/i;
    wx.getSystemInfo({
      success: function(res) {
        model = res.model;
      },
    })
    if (reg.test(model)) {
      model = 1
    } else model = 2;
    wx.setStorageSync('model', model);


    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })

    setTimeout(this.checkIMMessage, 2000);
  },
  connectWebsocket: function() {
    var that = this;
    console.log("请求链接");
    that.globalData.localSocket = wx.connectSocket({
      url: 'wss://' + base.host + '/webSocketServer.action',
      data: {},
      header: {
        'content-type': 'application/json',
        "Cookie": wx.getStorageSync("session")
      },
      method: "GET"
    })

    that.globalData.localSocket.onOpen(function(res) {
      console.log('WebSocket连接已打开！readyState=' + that.globalData.localSocket.readyState)
      var pare = {};
      var user = wx.getStorageSync("user");
      if (user != null && user != "") {
        pare['userId'] = user.aid
        pare['type'] = "handed"
        console.log(pare);

        // that.sendSocketMessage(JSON.stringify(pare));
      }

      /**while (socketMsgQueue.length > 0) {
        var msg = socketMsgQueue.shift();
        that.sendSocketMessage(msg);
      }**/

    })
    that.globalData.localSocket.onMessage(function(res) {

      that.globalData.callback(res)

    })

    that.globalData.localSocket.onError(function(res) {
      console.log('readyState=' + that.globalData.localSocket.readyState)
    })


    that.globalData.localSocket.onClose(function(res) {
      console.log('WebSocket连接已关闭！readyState=' + that.globalData.localSocket.readyState)
      that.connectWebsocket()
    })
  },
  //统一发送消息
  sendSocketMessage: function(msg) {
    if (this.globalData.localSocket.readyState === 1) {
      this.globalData.localSocket.send({
        data: JSON.stringify(msg)
      })
    } else {
      socketMsgQueue.push(msg)
    }
  },
  editTabBar: function() {
    var _curPageArr = getCurrentPages();
    var _curPage = _curPageArr[_curPageArr.length - 1];
    var _pagePath = _curPage.__route__;
    if (_pagePath.indexOf('/') != 0) {
      _pagePath = '/' + _pagePath;
    }
    var tabBar = this.globalData.tabBar;
    for (var i = 0; i < tabBar.list.length; i++) {
      tabBar.list[i].active = false;
      if (tabBar.list[i].pagePath == _pagePath) {
        tabBar.list[i].active = true; //根据页面地址设置当前页面状态    
      }
    }
    _curPage.setData({
      tabBar: tabBar
    });
  },
  //第二种状态的底部  
  editTabBar2: function() {
    var _curPageArr = getCurrentPages();
    var _curPage = _curPageArr[_curPageArr.length - 1];
    var _pagePath = _curPage.__route__;
    if (_pagePath.indexOf('/') != 0) {
      _pagePath = '/' + _pagePath;
    }
    var tabBar = this.globalData.tabBar2;
    for (var i = 0; i < tabBar.list.length; i++) {
      tabBar.list[i].active = false;
      if (tabBar.list[i].pagePath == _pagePath) {
        tabBar.list[i].active = true; //根据页面地址设置当前页面状态    
      }
    }
    _curPage.setData({
      tabBar: tabBar
    });
  },
  globalData: {
    userInfo: null,
    localSocket: {},
    callback: function() {},
    pop: 2,
    num: 0,
    tabBar: {
      "color": "#9E9E9E",
      "selectedColor": "#137AF0",
      "backgroundColor": "#fff",
      "borderStyle": "#ccc",
      "list": [{
          "pagePath": "/pages/gjIndex/gjindex/gjindex",
          "text": "首页",
          "iconPath": "../../../image/index.png",
          "selectedIconPath": "../../../image/index_cur.png",
          "clas": "menu-item",
          "selectedColor": "#137AF0",
          active: true
        },
        {
          "pagePath": "/pages/gjIndex/msg/msg",
          "text": "消息",
          "iconPath": "../../../image/msg.png",
          "selectedIconPath": "../../../image/msg_cur.png",
          "selectedColor": "#137AF0",
          "clas": "menu-item",
          active: false
        },
        {
          "pagePath": "/pages/gjIndex/gjorder/gjorder",
          "text": "订单",
          "iconPath": "../../../image/order.png",
          "selectedIconPath": "../../../image/order_cur.png",
          "selectedColor": "#137AF0",
          "clas": "menu-item",
          active: false
        },
        {
          "pagePath": "/pages/gjIndex/personal/personal",
          "text": "我的",
          "iconPath": "../../../image/pers.png",
          "selectedIconPath": "../../../image/pers_cur.png",
          "selectedColor": "#137AF0",
          "clas": "menu-item",
          active: false
        }
      ],
      "position": "bottom"
    },
    tabBar2: {
      "color": "#9E9E9E",
      "selectedColor": "#f00",
      "backgroundColor": "#fff",
      "borderStyle": "#ccc",
      "list": [{
          "pagePath": "/pages/index/index",
          "text": "首页",
          "iconPath": "/img/home.png",
          "selectedIconPath": "/img/home_on.png",
          "clas": "menu-item2",
          "selectedColor": "#4665f9",
          active: true
        },
        {
          "pagePath": "/pages/log/index",
          "text": "日志",
          "iconPath": "/img/home.png",
          "selectedIconPath": "/img/home_on.png",
          "selectedColor": "#4665f9",
          "clas": "menu-item2",
          active: false
        },
        {
          "pagePath": "/pages/my/index",
          "text": "我的",
          "iconPath": "../../../img/home.png",
          "selectedIconPath": "../../../img/home_on.png",
          "selectedColor": "#4665f9",
          "clas": "menu-item2",
          active: false
        },
        {
          "pagePath": "/pages/new/index",
          "text": "新的",
          "iconPath": "/img/home.png",
          "selectedIconPath": "/img/home_on.png",
          "selectedColor": "#4665f9",
          "clas": "menu-item2",
          active: false
        }
      ],
      "position": "bottom"
    },



    getUserInfo: function() {
      var that = this;
      var sessionId = wx.getStorageSync("session");
      wx.request({
        url: base.getUserInfo,
        header: {
          'content-type': 'application/json',
          'Cookie': sessionId
        },
        success: function(res) {
          console.log(res.data);
          wx.hideLoading();
          if (res.data.status == 200) {
            // wx.setStorageSync("session", res.data.data);
            //保存userInfo;
            var userInfo = res.data.data;
            //处理银行卡
            /**var cardNo = userInfo.membershipcard.cardNo;
            cardNo = cardNo.substring(0, 4) + "********" + cardNo.substring(cardNo.length - 4, cardNo.length);
            console.log(cardNo);
            userInfo.cardNumber = cardNo;**/
            wx.setStorageSync("user", userInfo);
            //与管家聊天封装
            var chatUser = {
              'accountByAid': {
                'name': userInfo.housekeeper.name
              }
            };
            wx.setStorageSync("chatUser", chatUser);
            if (userInfo.accountType.typeId == 1) {
              //普通用户跳转；
              console.log("普通用户跳转");
              setTimeout(function() {
                wx.switchTab({
                  url: '../index/index',
                })
              }, 1200);
            } else {
              //管家跳转；
              console.log("管家跳转");
              setTimeout(function() {
                wx.reLaunch({
                  url: '../gjIndex/gjindex/gjindex',
                })
              }, 1200);
            }

            var user = userInfo;
            /**if (user != null) {
              var pare = {};
              pare['userId'] = user.aid
              pare['type'] = "handed"
              that.sendSocketMessage(JSON.stringify(pare));
              console.log("发送完成");

            }**/

          }else{
            wx.reLaunch({
              url: '../login/login',
            })
          }
        },
        fail: function() {
          console.log("111");
          wx.hideLoading();
        }
      })
    }
  },
  checkIMMessage: function() {
    console.log("即时通讯信息");
    //即时通讯
    wx.request({
      url: base.chatOffLineMessageList,
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Cookie": wx.getStorageSync("session")
      },
      data: {
        start: 0,
        size: 10,
      },
      success: function(res) {
        console.log(res);
        if (res.statusCode == 200) {
          if (res.data.data != null && res.data.data.length != 0) {
            wx.showTabBarRedDot({
              index: 1,
            })
          }
        }
      }
    })
  },
  onShow: function() {
    console.log("进入前台");
    var that = this;
    if (this.globalData.localSocket.readyState !== 0 && this.globalData.localSocket.readyState !== 1) {
      console.log('开始尝试连接WebSocket！readyState=' + this.globalData.localSocket.readyState)
      that.connectWebsocket();
    }

    that.globalData.callback = function(res) {
      console.log('收到服务器内容：' + res.data)

      //解析消息 
      var json = JSON.parse(res.data);
      if (json.ntitle != null) {
        wx.showModal({
          title: json.ntitle,
          content: json.ncontent,
          success(e) {
            if (e.confirm) {
              if (json.isRead == "0") {
                wx.setStorageSync('orderConfirmType', 1);
                wx.setStorageSync('orderId', json.nid);
                wx.switchTab({
                  url: '../order/order',
                })
              } else {
                wx.setStorageSync('orderConfirmType', 1);
                wx.setStorageSync('orderId', json.nid);
                wx.navigateTo({
                  url: '../gjorder/gjorder',
                })
              }

            }
          }
        })
        // wx.setTabBarBadge({
        //   'index': 2,
        //   text: '1'
        // })

        wx.showTabBarRedDot({
          index: 1,
        })
      } else {
        wx.showTabBarRedDot({
          index: 1,
        })
      }
    }

  },
  onHide: function() {
    console.log("进入后台");
    //存储
    wx.setStorageSync("locationTimer", null);
    wx.setStorageSync("locationPoints", null);
  },
})